package at.fhj.itm11.forum.beans;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.faces.bean.ManagedBean;
import javax.inject.Inject;
import javax.inject.Named;

import at.fhj.itm11.forum.service.RatingService;
import at.fhj.itm11.forum.service.dtos.PostDTO;
import at.fhj.itm11.forum.service.dtos.RatingDTO;
import at.fhj.itm11.forum.service.dtos.UserDTO;
import at.fhj.itm11.forum.util.ForumConstants;

@ManagedBean
@RequestScoped
public class RatingBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -8808311719494761873L;

	@Inject
	@Named("authenticationBean")
	private AuthenticationBean authBean;

	@Inject
	@Named("ratingServiceImpl")
	private RatingService ratingService;

	@Produces
	private RatingDTO rating;
	
	private UserDTO rater;
	
	@PostConstruct
	public void init() {
		setRating(new RatingDTO());
		setRater((UserDTO) getAuthBean().getSession().getAttribute(
				ForumConstants.SESSION_CURRENT_USER));
		rating.setUser(rater);
	}
	
	public void ratePositively(PostDTO post) {
		rating.setPost(post);
		rating.setPositiveRating(true);
		getRatingService().rate(rating);
		refreshStatistics(post);
	}
	
	public void rateNegatively(PostDTO post) {
		rating.setPost(post);
		rating.setPositiveRating(false);
		ratingService.rate(rating);
		refreshStatistics(post);
	}
	
	public void refreshStatistics(PostDTO post) {
		int[] statistics = ratingService.getRatingStatistics(post.getId());
		post.setPercentageOfPositiveRatings(statistics[0]);
		post.setPercentageOfNegativeRatings(statistics[1]);
	}
	
	public AuthenticationBean getAuthBean() {
		return authBean;
	}

	public void setAuthBean(AuthenticationBean authBean) {
		this.authBean = authBean;
	}	
	
	public RatingService getRatingService() {
		return ratingService;
	}

	public void setRatingService(RatingService ratingService) {
		this.ratingService = ratingService;
	}

	public RatingDTO getRating() {
		return rating;
	}

	public void setRating(RatingDTO rating) {
		this.rating = rating;
	}

	public UserDTO getRater() {
		return rater;
	}

	public void setRater(UserDTO rater) {
		this.rater = rater;
	}
}
